/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nageoffer.shortlink.project.toolkit;

import cn.hutool.core.lang.hash.MurmurHash;

/**
 * HASH 工具类
 */
public class HashUtil {

    private static final char[] CHARS = new char[]{
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    };
    private static final int SIZE = CHARS.length;

    /**
     * 将十进制数字转换为Base62编码字符串
     * Base62编码使用62个字符（A-Z, a-z, 0-9）来表示十进制数字
     * 这种编码方式可以有效地将数字压缩成较短的字符串
     *
     * @param num 十进制数字，需要转换为Base62编码
     * @return 转换后的Base62编码字符串
     */
    private static String convertDecToBase62(long num) {
        StringBuilder sb = new StringBuilder();
        // 循环直到num为0，逐步将num转换为Base62编码
        while (num > 0) {
            // 计算num与SIZE的模，以确定在Base62字符集中的位置
            int i = (int) (num % SIZE);
            // 将计算出的Base62字符追加到字符串构建器中
            sb.append(CHARS[i]);
            // 将num除以SIZE，为下一轮循环做准备
            num /= SIZE;
        }
        // 由于Base62编码构建过程是逆序的，需要反转字符串后才能得到正确的编码
        return sb.reverse().toString();
    }

    /**
     * 将字符串哈希到Base62编码
     * 此方法首先使用MurmurHash算法对输入字符串进行哈希处理，然后将得到的哈希值转换为Base62编码字符串
     * Base62编码使用0-9、a-z、A-Z共62个字符来表示值，适用于短网址服务等场景
     *
     * @param str 待哈希的原始字符串
     * @return 哈希后的Base62编码字符串
     */
    public static String hashToBase62(String str) {
        // 使用MurmurHash算法对字符串进行哈希处理，得到一个整数
        int i = MurmurHash.hash32(str);
        // 根据哈希值的正负决定最终转换的数值，确保结果为正数
        long num = i < 0 ? Integer.MAX_VALUE - (long) i : i;
        // 将得到的数值转换为Base62编码字符串并返回
        return convertDecToBase62(num);
    }
}